<template>
  <div class="app-container">
    <el-card shadow="never" v-loading="loading">
      <el-row :gutter="5">
        <el-col :span="24" class="main-card-view">
          <el-row >
            <el-card shadow="never" class="top-search-view-card">
              <el-row>
                <el-form :inline="true" :model="searchForm" class="demo-form-inline search-view">
                  <el-form-item label="机构名称">
                    <el-input v-model="searchForm.organName" placeholder="请输入机构名称"></el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="handleSearch" class="search-button">查询
                    </el-button>
                   <el-button type="primary" @click="showCreateDialog" class="new-button" >新建
                    </el-button>
                  </el-form-item>
                </el-form>
              </el-row>
            </el-card>
          </el-row>

          <el-row>
            <el-card shadow="never">
              <el-table :data="tableData" :stripe="true" style="width: 100%">
                <el-table-column prop="organName" align="center" label="机构名称" />
                <el-table-column prop="summaryFileStr" align="center" label="汇总文件" />
                <el-table-column align="center" label="操作" width="300">
                  <template slot-scope="scope">
                   <el-button type="text" @click="showEditDialog(scope.row)">编辑</el-button>
                   <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
                   <el-button type="text" @click="downLoad(scope.row.summaryFile)" v-if="scope.row.summaryFile" >下载pdf</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <XPagination ref="pageInfo" :total="total" :get-data="getList" />
            </el-card>
          </el-row>
        </el-col>
      </el-row>
    </el-card>

    <el-dialog width="40%" title="pdf下载" :visible.sync="attachmentsDialog">
            <el-table :data="attachmentsList" :stripe="true" style="width: 100%">
                <el-table-column prop="originName" align="center" label="机构名称" />
                <el-table-column align="center" label="操作" width="200">
                    <template slot-scope="scope">
                        <el-button @click="downLoad(scope.row.summaryFile)" type="text">下载</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <template slot="footer">
                <el-button type="primary" @click="attachmentsDialog = false">关闭</el-button>
            </template>
        </el-dialog>

     <el-dialog width="80%" :title="dialogTitle" :visible.sync="dialogVisible">
       <el-form label-width="150px" ref="form" :model="form">
         <el-tabs>
           <el-tab-pane label="汇总表" />
         </el-tabs>
         <el-row :gutter="60">
           <el-col :span="12">
             <el-form-item label="机构名称" prop="organName">
               <el-input v-model="form.organName">
                 <template slot="append">
                   <el-button @click="openOrgList">选择机构</el-button>
                 </template>
               </el-input>
             </el-form-item>

           </el-col>
           <el-col :span="12">
             <el-form-item label="汇总文件" prop="summaryFile">
               <upLoadPdfa  v-model="form.summaryFile"></upLoadPdfa>
               <span style="color: #01c7ab;cursor:pointer" v-if="form.summaryFile && form.uid" @click="downLoad(form.summaryFile)">已上传(点击下载)</span>
             </el-form-item>
           </el-col>
         </el-row>
         </el-row>
       </el-form>
       <template slot="footer">
         <el-button type="primary" @click="handleSave">保存</el-button>
       </template>
     </el-dialog>

     <el-dialog title="专家信息" :visible.sync="dialogTableVisible" width="85%">
       <el-card shadow="never" v-loading="loading">
         <el-row :gutter="5">
           <el-col :span="24" class="main-card-view">
             <el-row>
               <el-card shadow="never" class="top-search-card">
                 <el-row>
                   <el-form :inline="true" :model="searchOrgForm" class="demo-form-inline search-view">
                     <el-form-item label="机构名称">
                       <el-input v-model="searchOrgForm.organName" placeholder="请输入机构名称"></el-input>
                     </el-form-item>
                     <el-form-item label="级别">
                      <el-select style="width: 100%;" v-model="searchForm.grade" clearable>
                        <el-option v-for="(item) in gradeList" :key="item.uid" :label="item.name" :value="item.name" />
                      </el-select>
                     </el-form-item>

                     <el-form-item>
                       <el-button type="primary" @click="handleOrgSearch" class="search-button">
                         查询
                       </el-button>
                     </el-form-item>
                   </el-form>
                 </el-row>
               </el-card>
             </el-row>

             <el-row>
               <el-card shadow="never">
                 <el-table :data="tableOrgData" :stripe="true" style="width: 100%">
                   <el-table-column prop="classification" align="center" label="机构分类" />
                   <el-table-column prop="organName" align="center" label="机构名称" />
                   <el-table-column prop="grade" align="center" label="级别" />
                   <el-table-column prop="phone" align="center" label="电话" />
                   <el-table-column prop="area" align="center" label="区域">
                     <template slot-scope="scope">
                       {{ [scope.row.province, scope.row.city, scope.row.area].join(">") }}
                     </template>
                   </el-table-column>
                   <el-table-column prop="dependency" align="center" label="等级"/>
                   <el-table-column align="center" label="操作" width="200">
                     <template slot-scope="scope">
                       <el-button type="text" @click="selectOrg(scope.$index, scope.row)">选择
                       </el-button><!--编辑-->
                     </template>
                   </el-table-column>
                 </el-table>
                 <XPagination ref="orgPageInfo" :total="orgTotal" :get-data="getOrgList" />
               </el-card>
             </el-row>
           </el-col>
         </el-row>
       </el-card>
     </el-dialog>

  </div>
</template>

<script>
import XPagination from "../../components/xpagination/XPagination"
import * as summaryInfo from "../../api/summaryInfo"
import * as formUtils from "../../utils/formUtils"
import XUpload from "../../components/xupload/XUpload"
import * as myDownload from "../../api/myDownload"
import uploadAttachments from "../../components/uploadAttachments.vue"
import upLoadPdfa from "../../components/upLoadPdfa.vue"
import * as organInfo from "../../api/organInfo";
export default {
  name: "summaryInfo",
  components: { XUpload, XPagination,uploadAttachments,myDownload, upLoadPdfa },
  data () {
    return {
      selectionData: [],
      searchForm: {
        name: "",
        organName: "",
        departmentName: "",
      },
      gradeList: [],
      tableData: [],
      loading: false,
      dialogVisible: false,
      userInfo: JSON.parse(localStorage.getItem("user_info")),
      total: 0,
      dialogTitle: "添加汇总文件",
      form: {
        uid: "",
        organName: "",
        summaryFile: "",

      },
      editStatus: "add",

      // 机构管理信息
      dialogTableVisible: false,
      searchOrgForm: {
        creditIdentifier: "",
        grade: "",
        organName: "",
        unitName: "",
      },
      tableOrgData: [],
      orgTotal: 0,
      regionOptions: [],
      dialogPwsVisible: false,
      attachmentsDialog:false,
      attachmentsList:[]
    }
  },
  methods: {
      downLoad(url){
          const a = document.createElement('a')
          a.style.display = 'none'
          url=url.replace('http:','https:')
          a.download = url
          a.href = url
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
      },

      getOrgList (pageInfo) {
        const param = {
          ...this.searchOrgForm,
          ...pageInfo
        }
        if(this.userInfo.roleName==='机构'){
            param.organName=this.userInfo.userName
        }

        organInfo.queryByPage(param).then(response => {
          console.log(response)
          this.tableOrgData = response.data.data.rows
          this.orgTotal = response.data.data.total
          this.loading = false
        }).catch(error => {
          console.log(error)
        })
      },
      openOrgList () {
        this.getOrgList();
        this.dialogTableVisible = true;
      },

      selectOrg (index, data) {
        this.form.organName = data.organName;
        this.dialogTableVisible = false;
      },

    excExport(){
        let sheetData = []
        let datas=[]
        if(this.selectionData.length>0){
            datas=this.selectionData
        }else{
            datas=this.tableData
        }
        sheetData = datas.map(item => ({
            '专家名称': item.name,
            '推荐单位': item.organName,
            '工作单位': item.workUnit||item.organName,
            '科室': item.departmentName,
            '职务': item.position,
            '电话': item.telNum||item.officePhone,
            '等级': item.dependency,
            '状态': item.status,
        }))
        const wb = XLSX.utils.book_new();
        const ws = XLSX.utils.json_to_sheet(sheetData);
        XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
        XLSX.writeFile(wb, 'user_data.xlsx');
    },
    exportPdf(uid){
        summaryInfo.queryById(uid).then(response=>{
            if(response.data.code==200 && response.data.data.summaryFile){
                const a = document.createElement('a')
                a.style.display = 'none'
                a.download = response.data.data.summaryFile
                if(!response.data.data.summaryFile.includes("https")){
                    response.data.data.summaryFile=response.data.data.summaryFile.replace('http','https');
                }
                a.href = response.data.data.summaryFile
                document.body.appendChild(a)
                a.click()
                document.body.removeChild(a)
            }else{
                 this.$message.error("无pdf文件")
            }
        })
    },
    loadPdf (data) {
        this.form = Object.assign({}, data)
        this.attachmentsDialog = true
        expertInfo.queryFileInf({ fileUrl: data.highestEducationLevel }).then(result => {
            this.attachmentsList = result.data.data.rows
            console.log("data.uid-->"+this.attachmentsList)
        }).catch(error => {
            this.$message.error(error)
            console.log(error)
        })
    },
    getList (pageInfo) {
      const param = {
        ...this.searchForm,
        ...pageInfo
      }
      if(this.userInfo.roleName==='机构'){
          param.organName=this.userInfo.userName
      }

      summaryInfo.queryByPage(param).then(response => {
        console.log(response)
        response.data.data.rows.forEach(item=>{
            if(item.summaryFile){
                item.summaryFileStr='专家汇总表.pdf'
            }else{
                item.summaryFileStr='未上传'
            }
        })
        this.tableData = response.data.data.rows
        this.total = response.data.data.total
        this.loading = false
      }).catch(error => {
        console.log(error)
      })
    },


    handleDelete (data) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const param = {
          uid: data.uid,
        }
        this.loading = true
        summaryInfo.deleteById(param).then(result => {
          this.loading = false
          this.$message.success(result.data.msg)
          this.handleSearch()
        }).catch(error => {
          this.loading = false
          console.log(error)
        })
      }).catch(() => {
        console.log('取消删除')
      });
    },

    handleSearch () {
      this.$refs.pageInfo.loadData()
    },
    showCreateDialog () {
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.dialogTitle = "添加汇总文件"
        this.editStatus = "add"
        this.$refs.form.resetFields()
        this.form = Object.assign({}, this.$options.data().form)
      })
    },
    handleSave () {
      if (this.editStatus === "add") {
        this.handleAdd()
      } else {
        this.handleEdit()
      }
    },
    handleAdd () {
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          return false
        }
        const param = Object.assign({}, this.form)
        formUtils.filterFormFields(param)
        summaryInfo.insert(param).then(result => {
          this.$message.success(result.data.msg)
          this.dialogVisible = false
          this.handleSearch()
        }).catch(error => {
          this.$message.error(error)
          console.log(error)
        })

      })
    },
    handleEdit () {
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          return false
        }
        const param = Object.assign({}, this.form)
        formUtils.filterFormFields(param)
        summaryInfo.update(param).then(result => {
          this.$message.success(result.data.msg)
          this.dialogVisible = false
          this.dialogPwsVisible = false
          this.handleSearch()
        }).catch(error => {
          this.$message.error(error)
          console.log(error)
        })
      })
    },
    showEditDialog (data) {
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.form.resetFields()
        this.form = Object.assign({}, data)
        this.dialogTitle = "编辑汇总文件"
        this.editStatus = "edit"
      })
    },
    uploadDialog (index, data) {
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.form.resetFields()
        this.form = Object.assign({}, data)
        this.dialogTitle = "编辑汇总文件"
        this.editStatus = "edit"
      })
    },

    handleOrgSearch () {
      this.$refs.orgPageInfo.loadData()
    },
  },
  mounted () {
    this.handleSearch()
  }
}
</script>

<style scoped lang="scss"></style>
